package org.example;

import org.apache.commons.io.FileUtils;
import org.example.exception.ExceptionReporter;
import org.example.utlis.FXUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

public class ConfigLoader {
    private Properties prop;
    private final String propPath = "../../config/settings.properties";
    private final String KEY_ALL_TRACE_TAG = "trace_tag_all";
    private final String DEFAULT_VALUE_ALL_TRACE_TAG = "";
    public void loadProperties() throws IOException {
        prop = new Properties();
        File file = new File(propPath);
        System.out.println(file.getPath());
        if (!file.exists()) {
            FileUtils.forceMkdirParent(file);
            file.createNewFile();
        }
        FileInputStream fileInputStream = new FileInputStream(propPath);
        prop.load(fileInputStream);
//        prop.list(System.out);
    }

    private void init(String[] keys) {
        for (String key : keys) {
            String value = get(key);
            if (value != null) {
                continue;
            }
            String defaultValue = "";
            switch (key) {
                case KEY_ALL_TRACE_TAG:
                    defaultValue =  DEFAULT_VALUE_ALL_TRACE_TAG;
                    break;
                default:
                    break;
            }
            put(key, defaultValue);
        }
    }

    public String get(String key) {
        return prop.getProperty(key);
    }

    public void put(String key, String value) {
        if (value == null || value.isEmpty()) {
            return;
        }
        try {
            OutputStream outputStream = Files.newOutputStream(Paths.get(propPath));
            prop.setProperty(key, value);
            prop.store(outputStream, null);
            outputStream.close();
        } catch (Exception e) {
            ExceptionReporter.saveLog(e, true);
        }

    }
}
